package com.tally.business.controller;

import com.alibaba.fastjson.JSONObject;
import com.tally.server.dto.MessageDTO;
import com.tally.server.dto.PageDTO;
import com.tally.server.dto.ResponseDTO;
import com.tally.server.service.MessageService;
import com.tally.server.utils.ValidatorUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @Author: sy
 * @Date: 2020/11/13 20:13
 * @Description:
 */
@RestController
@RequestMapping("/message")
public class MessageController extends BusinessController {

    private static final Logger logger = LoggerFactory.getLogger(MessageController.class);
    public static final String BUSINESS_NAME = "消息";

    @Autowired
    private MessageService messageService;

    /**
     * 列表查询
     * @param pageDTO
     * @return
     */
    @PostMapping("/list")
    public ResponseDTO list(@RequestBody PageDTO pageDTO){
        JSONObject loginUser = getLoginUser();
        messageService.list(pageDTO, loginUser.getInteger("id"));
        return ResponseDTO.success(pageDTO);
    }

    /**
     * 保存，id有值时更新，无值时新增
     * @param messageDTO
     * @return
     */
    @PostMapping("/save")
    public ResponseDTO save(@RequestBody MessageDTO messageDTO){
        // 保存校验
        ValidatorUtil.require(messageDTO.getSendUserId(),"发送者id");
        ValidatorUtil.require(messageDTO.getRecUserId(),"接收者id");
        ValidatorUtil.require(messageDTO.getType(),"类型，点赞L，评论C，回复R");
        ValidatorUtil.require(messageDTO.getPostId(),"文章id");

        messageService.save(messageDTO);
        return ResponseDTO.success(messageDTO);
    }

    @PostMapping("/changeRead")
    public ResponseDTO changeRead(@RequestBody MessageDTO messageDTO) {
        messageService.updateSelective(messageDTO);
        return ResponseDTO.success(null);
    }

    @PostMapping("/send")
    public ResponseDTO sendMessage(@RequestBody MessageDTO messageDTO) {
        messageService.save(messageDTO);
        return ResponseDTO.success(null);
    }

    @GetMapping("/countUnread")
    public ResponseDTO countUnread() {
        JSONObject jsonObject = getLoginUser();
        Long num = messageService.countUnread(jsonObject.getInteger("id"));
        return ResponseDTO.success(num);
    }
}
